﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Models;

namespace Service
{
    public class ItemManager : IServiceMnanger, IItemManager
    {
        public IList<ItemInfo> GetItemInfoByMID(int mid)
        {
            var obj = from o in context.ItemInfo
                      where o.MID == mid
                      orderby o.CreateDate descending
                      select o;

            return obj != null ? obj.ToList() : null;
        }

        public ItemInfo GetItemInfoByID(int id)
        {
            var obj = from o in context.ItemInfo
                      where o.ID == id
                      select o;

            return obj != null ? obj.ToList().FirstOrDefault() : null;
        }

        public IList<ItemInfo> GetItemInfoByEnity(ItemInfo parObj)
        {
            var obj = from o in context.ItemInfo
                      select o;
            if (parObj != null)
            {
                obj = parObj.ID == 0 ? obj : obj.Where<ItemInfo>(o => o.ID == parObj.ID);
                obj = parObj.MID == null ? obj : obj.Where<ItemInfo>(o => o.MID == parObj.MID);
                obj = parObj.Title == null ? obj : obj.Where<ItemInfo>(o => o.Title == parObj.Title);
                obj = parObj.Status == null ? obj : obj.Where<ItemInfo>(o => o.Status == parObj.Status);
                obj = parObj.Body == null ? obj : obj.Where<ItemInfo>(o => o.Body == parObj.Body);
                obj = parObj.Author == null ? obj : obj.Where<ItemInfo>(o => o.Author == parObj.Author);
                obj = parObj.Origin == null ? obj : obj.Where<ItemInfo>(o => o.Origin == parObj.Origin);
                obj = parObj.CreateBy == null ? obj : obj.Where<ItemInfo>(o => o.CreateBy == parObj.CreateBy);
                obj = parObj.CreateDate == null ? obj : obj.Where<ItemInfo>(o => o.CreateDate == parObj.CreateDate);
            }
            return obj != null ? obj.OrderByDescending(o => o.CreateDate).ToList() : null;
        }

        public int DoSaveChanges(ItemInfo parObj)
        {
            parObj = parObj ?? new ItemInfo();
            ItemInfo obj = GetItemInfoByID(parObj.ID);
            if (obj == null)
            {
                obj = new ItemInfo();
                context.AddToItemInfo(obj);
            }

            obj.MID = parObj.MID ?? obj.MID;
            obj.Title = parObj.Title ?? obj.Title;
            obj.Status = parObj.Status ?? obj.Status;
            obj.Body = parObj.Body ?? obj.Body;
            obj.Author = parObj.Author ?? obj.Author;
            obj.Origin = parObj.Origin ?? obj.Origin;
            obj.CreateBy = parObj.CreateBy ?? obj.CreateBy;
            obj.CreateDate = parObj.CreateDate ?? obj.CreateDate ?? DateTime.Now;

            return context.SaveChanges();
        }
    }
}
